// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//
#pragma once

#include <cstdint>
#include <cstring>

namespace kumo::pollux::common {
    struct OutputByteStream {
        explicit OutputByteStream(char *data, int32_t offset = 0)
            : data_(data), offset_{offset} {
        }

        template<typename T>
        void appendOne(T value) {
            *reinterpret_cast<T *>(data_ + offset_) = value;
            offset_ += sizeof(T);
        }

        void append(const char *data, int32_t size) {
            memcpy(data_ + offset_, data, size);
            offset_ += size;
        }

        int32_t offset() const {
            return offset_;
        }

    private:
        char *data_;
        int32_t offset_;
    };

    struct InputByteStream {
        explicit InputByteStream(const char *data) : data_(data) {
        }

        template<typename T>
        T read() {
            T value = *reinterpret_cast<const T *>(data_ + offset_);
            offset_ += sizeof(T);
            return value;
        }

        template<typename T>
        void copyTo(T *destination, int size) {
            memcpy(
                reinterpret_cast<char *>(destination),
                data_ + offset_,
                size * sizeof(T));
            offset_ += size * sizeof(T);
        }

        template<typename T>
        const T *read(int size) {
            auto result = reinterpret_cast<const T *>(data_ + offset_);
            offset_ += size * sizeof(T);
            return result;
        }

        int32_t offset() const {
            return offset_;
        }

    private:
        const char *data_;
        int32_t offset_{0};
    };
} // namespace kumo::pollux::common
